package com.yu.smsinterceptor;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;

import com.yu.smsinterceptor.mode.Message;
import com.yu.smsinterceptor.service.MessageService;
import com.yu.smsinterceptor.service.PhoneService;

import java.util.Date;
import java.util.List;

/**
 * 短信广播接收者
 */
public class MessageReceiver extends BroadcastReceiver {

    private PhoneService phoneService = new PhoneService();
    private MessageService messageService = new MessageService();

    @Override
    public void onReceive(Context context, Intent intent) {
        //获取所有要拦截的号码
        List<Long> numbers = phoneService.listPhoneNumber();

        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        for (Object pdu : pdus) {
            //将pdu中的对象转换成SmsMessage对象
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
            //获取发送者手机号码
            String sender = smsMessage.getOriginatingAddress();

            for (Long number : numbers) {
                if (sender.equals(number.toString())) {
                    String messageBody = smsMessage.getMessageBody();
                    Message msg = new Message();
                    msg.setPhone(Long.valueOf(sender));
                    msg.setContent(messageBody);
                    msg.setReceiverTime(new Date());
                    messageService.save(msg);
                }
            }
        }
    }
}
